package com.sl.proxy.client.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.sl.proxy.client.config.ProxyClientConfig;
import com.sl.proxy.core.Constants;
import com.sl.proxy.core.ExceptionEnum;
import com.sl.proxy.core.ProxyMessage;
import com.sl.proxy.core.ProxyMessageHandler;
import com.sl.proxy.core.dispatcher.Match;
import io.netty.channel.ChannelHandlerContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.springframework.aop.framework.ProxyConfig;
import org.springframework.stereotype.Component;

/**
 * 认证信息处理器
 *
 * @author: aoshiguchen
 * @date: 2022/9/4
 */
@Slf4j
@Match(type = Constants.ProxyDataTypeName.AUTH)
@RequiredArgsConstructor
public class ProxyMessageAuthHandler implements ProxyClientMessageHandler {
    private final ProxyClientConfig proxyConfig;

    @Override
    public void handle(ChannelHandlerContext context, ProxyMessage proxyMessage) {
        String info = proxyMessage.getInfo();
        ONode load = ONode.load(info);
        Integer code = load.get("code").getInt();
        log.info("Auth result:{}", info);
        if (ExceptionEnum.AUTH_FAILED.getCode().equals(code)) {
            // 客户端认证失败，直接停止服务
            log.info("client auth failed , client stop.");
            context.channel().close();
            if (!proxyConfig.getTunnel().getReconnection().getUnlimited()) {
//                Solon.stop();
                return;
            }
        } else if (ExceptionEnum.CONNECT_FAILED.getCode().equals(code) ||
                ExceptionEnum.LICENSE_CANNOT_REPEAT_CONNECT.getCode().equals(code)
        ) {
            context.channel().close();
        }
    }
}
